import React, { useState } from "react";
import { Button, List, Modal } from "antd";
import { userDeleteFolderArticle } from "@/apis/userApi";
import { useDispatch } from "react-redux";
import { deleteUserCollectionArticle } from "@/store/UserInfo/index.ts";
import { CollectItem } from "@/apis/shared.ts";

interface Props {
  folderName: string;
  collectItem: CollectItem[];
  reloadData: () => void;
}

const UserCollectionItemToChange: React.FC<Props> = ({
  collectItem,
  folderName,
  reloadData,
}) => {
  const dispatch = useDispatch();
  // 弹出框状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 设置要删除的文章
  const [articleIdToDelete, setArticleIdToDelete] = useState("");

  // 显示弹出框
  const showModal = (articleId: string) => {
    // 设置要删除的文章
    setArticleIdToDelete(articleId);
    // 显示弹出框
    setIsModalOpen(true);
  };

  // 点击确认按钮
  const handleOk = async () => {
    // 调用api删除文章
    const res = await userDeleteFolderArticle(folderName, articleIdToDelete);

    // 文章删除成功
    if (res.code === 200) {
      // 删除文章成功
      reloadData();
    }

    // 更新 redux 中的数据
    dispatch(
      deleteUserCollectionArticle({
        folderName: folderName,
        _id: articleIdToDelete,
      })
    );

    // 打印日志
    console.log("收藏夹中的文章删除成功");

    // 重置删除的文章
    setArticleIdToDelete("");

    // 关闭弹出框
    setIsModalOpen(false);
  };

  // 点击取消按钮
  const handleCancel = () => {
    // 重置删除的文章
    setArticleIdToDelete("");
    // 关闭弹出框
    setIsModalOpen(false);
  };

  return (
    <div>
      {collectItem.length === 0 ? (
        <div>暂无文章</div>
      ) : (
        <List
          size="small"
          bordered
          dataSource={collectItem.length > 0 ? collectItem : []}
          renderItem={(item) => (
            <List.Item key={item._id}>
              <List.Item.Meta
                title={
                  <a href={`/layout/article?_id=${item._id}`}>{item.title}</a>
                }
                description={item.summary}
              />
              <Button type="link" onClick={() => showModal(item._id)}>
                删除文章
              </Button>
            </List.Item>
          )}
        />
      )}
      <Modal
        title="注意"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>确定要删除该文章吗？</p>
      </Modal>
    </div>
  );
};

export default UserCollectionItemToChange;
